package com.handpay.zztong.hp.trans.activity;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DateUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.adapter.FastTransferAdapter;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.Bill;
import com.handpay.zztong.hp.config.UPConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.paymentbill.model.bill.QueryTransactionBillsBean;
import com.handpay.zztong.hp.paymentbill.model.bill.QueryTransactionBillsModel;
import com.handpay.zztong.hp.paymentbill.widget.CalendarDialogView;
import com.handpay.zztong.hp.paymentbill.widget.CalendarView;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.SwiperCardProgress;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.webpay.model.AccountTransfer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;

/**
 * 卡包管理和转账流水（快速转账）
 *
 * @author jjyang
 */
public class FastTransferActivity extends ZZTongActivity implements CalendarView.OnItemClickListener {

    private final static String TAG = "FastTransferActivity";
    private ZZTShowDialog<CalendarDialogView> mCalendarDialog;

    private boolean isDatePickerDialog4StartDate = false;

    // 起始日期
    private Date startDate;
    // 结束日期
    private Date endDate;
    // 起始日期控件
    private TextView startDateShowTextView;

    // 结束日期控件
    private TextView endDateShowTextView;
    private FastTransferAdapter fastTransferAdapter;
    // 交易账单列表
    private List<Bill> bills;
    private TextView title;
    //	private TextView tabs_hint, tabs_iv;
    private ListView fast_queryBillsListView;
    //	private LinearLayout fast_cardpackage, fast_transfer_flow, tabs_llo;
    private FastTransferActivity context;
    // 总金额,总笔数
    private TextView tvAmounts, tvItems;
    private LinearLayout queryBillsListViewFooterView;
    // 页码信息
    private TextView tvPageInfo;
    // 分页按钮
    private Button btnLast;
    private Button btnNext;
    private Button btnIndex;
    private Button btnEnd;
    private static final String[] transStatusType = {"全部", "交易成功", "交易失败", "交易处理中"};
    private Spinner spinnerTransStatus;
    private ArrayAdapter<String> adapter;
    private String transStatus;
    private int pageNo = 1;
    private int totalPages = -1;
    //    private ListCardPackAdapter mCardsAdapter;
    // 标志刷卡器处于的状态. BANK_LIST,获取bank列表; DELETE_BANK 删除bank.
    private final int IDLE = -1;
    private final int BANK_LIST = 0;
    private final int DELETE_BANK = 1;
    private final int CHECK_MAC = 2;
    private byte mStatus = IDLE;
    private String mServiceInfo;
    private int mDeletePos;
    private Hashtable<String, String> mRespData;
    private ImageView mRight_bar = null;
    private SwiperCardProgress siExplain;
    private LinearLayout ll_amount_pages;
    private int curr_position = 0;

//    private OnDeleteItemListener mDeleteListener = new OnDeleteItemListener() {
//        @Override
//        public void deleteItem(int position) {
//            deleteCard(position);
//        }
//    };

    @Override
    protected boolean isShownTabs() {

        return false;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.tranfers_flow), true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.fast_transfer_cardpackage);
        super.onCreate(savedInstanceState);

        final Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        this.mAction = getIntent().getByteExtra(ACTION, Action_SuperUniTrans);
        HPLog.e("FastTransferActivity--flow", "mAction----" + mAction);

        context = this;
        mCalendarDialog = new ZZTShowDialog<CalendarDialogView>(this, new CalendarDialogView(this), R.style.dialog);
        mCalendarDialog.getContentView().getCalendar().setOnItemClickListener(this);
//		this.datePicker = new DatePicker(this);
//		this.datePickerDialog = new AlertDialog.Builder(this).setTitle(R.string.select_date).setView(this.datePicker).setPositiveButton(R.string.ok, this).setNegativeButton(R.string.cancel, this).create();

//		tabs_llo = (LinearLayout) findViewById(R.id.tabs_llo);
//		fast_cardpackage = (LinearLayout) findViewById(R.id.fast_transfer_cardpackage);
//		fast_transfer_flow = (LinearLayout) findViewById(R.id.fast_transfer_flow);
//		tabs_iv = (TextView) findViewById(R.id.tabs_iv);
//		tabs_hint = (TextView) findViewById(R.id.tabs_hint);
        // 信用卡还款
//        if (mAction == Action_CreditCardRepay) {
//			tabs_hint.setText(R.string.repayment_flow);
//            myActionBar.setTitleText(R.string.repayment_Creditcard);
//        }
//		Card_package_list = (ListView) findViewById(R.id.Card_package_list);
        fast_queryBillsListView = (ListView) findViewById(R.id.fast_queryBillsListView);
//		siExplain = (SwiperCardProgress) this.findViewById(R.id.siExplain);
//        mCardsAdapter = new ListCardPackAdapter(this, R.layout.delete_layout);
//        mCardsAdapter.setDeleteListener(mDeleteListener);

        LayoutInflater inflater = LayoutInflater.from(this);
        this.queryBillsListViewFooterView = (LinearLayout) inflater.inflate(R.layout.layout_more_item, null);
        this.tvPageInfo = (TextView) queryBillsListViewFooterView.findViewById(R.id.tvPageInfo);
        this.btnIndex = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnIndex);
        this.btnEnd = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnEnd);
        this.btnLast = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnLast);
        this.btnNext = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnNext);
        this.btnIndex.setOnClickListener(this);
        this.btnEnd.setOnClickListener(this);
        this.btnLast.setOnClickListener(this);
        this.btnNext.setOnClickListener(this);

        fast_queryBillsListView.addFooterView(this.queryBillsListViewFooterView);
        LinearLayout headerView = (LinearLayout) inflater.inflate(R.layout.layout_querybills_header, null);
        //隐藏撤销状态，交易类型，流水单号
        headerView.findViewById(R.id.trans_mode).setVisibility(View.GONE);
        headerView.findViewById(R.id.bacthRow).setVisibility(View.GONE);
        headerView.findViewById(R.id.revoke_status).setVisibility(View.GONE);
        (headerView.findViewById(R.id.queryButton)).setOnClickListener(this);
        (headerView.findViewById(R.id.startDateRow)).setOnClickListener(this);
        (headerView.findViewById(R.id.endDateRow)).setOnClickListener(this);
        spinnerTransStatus = (Spinner) headerView.findViewById(R.id.transStatus_spinner);
        adapter = new ArrayAdapter<String>(this, R.layout.myspinnerdropdown, transStatusType);
        spinnerTransStatus.setAdapter(adapter);
        // 添加事件Spinner事件监听
        spinnerTransStatus.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                HPLog.e("queryBills========", "position:" + position);
                if (position == 0) {
                    transStatus = null;// null 全部
                } else if (position == 1) {
                    transStatus = "1";// 1表示成功，
                } else if (position == 2) {
                    transStatus = "0";// 0表示失败，
                } else if (position == 3) {
                    transStatus = "2";// 3交易处理中
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        Date today = DateUtils.formatStringToDate(DateUtils.formatDateToString(new Date(), "yyyyMMdd"), "yyyyMMdd");
        this.startDateShowTextView = (TextView) headerView.findViewById(R.id.startDateShowTextView);
        this.endDateShowTextView = (TextView) headerView.findViewById(R.id.endDateShowTextView);

        this.startDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));
        this.startDate = today;
        this.endDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));
        this.endDate = new Date(today.getTime() + (24 * 60 * 60 * 1000) - 1);
        this.fast_queryBillsListView.addHeaderView(headerView);
        this.fast_queryBillsListView.setAdapter(null);
        ll_amount_pages = (LinearLayout) headerView.findViewById(R.id.ll_amount_pages);
        tvAmounts = (TextView) headerView.findViewById(R.id.tvAmounts);
        tvAmounts.setText("");
        tvItems = (TextView) headerView.findViewById(R.id.tvItems);
        tvItems.setText("");
        fastTransferAdapter = new FastTransferAdapter(this);
        bills = new ArrayList<>();
//        mRight_bar = new ImageView(this);
//        mRight_bar.setBackgroundResource(R.drawable.edit_zzt);
//        mRight_bar.setVisibility(View.GONE);
//        mRight_bar.setPadding(0, 0, 20, 0);
//        myActionBar.addView(mRight_bar);
//        mRight_bar.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                boolean isAllShown = mCardsAdapter.isAllShown();
//                mCardsAdapter.showOrHideAllDeleteIcon(!isAllShown);
//            }
//        });

//		tabs_iv.setOnClickListener(this);
//		tabs_hint.setOnClickListener(this);
//		tabs_llo.setOnClickListener(this);
        // com.handpay.framework.utils.ViewServer.get(this).addWindow(this);
    }


    private void queryCards() {
        if (IDLE != mStatus) {
            HPLog.i(TAG, "cancel queryCard. status error!");
            return;
        }
        showProgressDialog(this, getResources().getString(R.string.pleasewait));
        mStatus = BANK_LIST;
        mServiceInfo = UPConfig.PREV_QUERY_BANKCARD;
        doBankListMac();
    }


    private void doMacCheck(String macPlain, Hashtable<String, String> responseData) {
        if (DELETE_BANK != mStatus && BANK_LIST != mStatus) {
            HPLog.i(TAG, "cancel doMacCheck. status error!");
            return;
        }
        showProgressDialog(this, getResources().getString(R.string.pleasewait));
        mStatus = CHECK_MAC;
        mRespData = responseData;
        doMac(macPlain);
    }

    private String getRespData(String key, Hashtable<String, String> respData) {
        return respData.get(key.toLowerCase(Locale.US));
    }


    private void resetStatus() {
        // 恢复状态到原始
        clearFactor();
        this.mRespData = null;
        this.mServiceInfo = null;
        this.mDeletePos = -1;
        mStatus = IDLE;
    }

    @Override
    protected void goBack() {
        clearFactor();
        stopAdpu();
        super.goBack();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int i = v.getId();
        if (i == R.id.startDateRow) {
            // this.isDatePickerDialog4StartDate = true;
            // this.datePickerDialog.show();
            this.isDatePickerDialog4StartDate = true;
            mCalendarDialog.getContentView().setCalendarData(startDate);
            mCalendarDialog.show();
        } else if (i == R.id.endDateRow) {
            // this.isDatePickerDialog4StartDate = false;
            // this.datePickerDialog.show();
            this.isDatePickerDialog4StartDate = false;
            mCalendarDialog.getContentView().setCalendarData(endDate);
            mCalendarDialog.show();
        } else if (i == R.id.queryButton || i == R.id.btnIndex) {
            pageNo = 1;
            if (DateUtils.isOkDate(this, startDate, endDate) == true) {
                if (DateUtils.changequerystate(startDate, endDate)) {
                    // 查询
                    doNet();
                } else {
                    this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }

        } else if (i == R.id.btnNext) {
            pageNo++;
            if (DateUtils.isOkDate(this, startDate, endDate) == true) {
                if (DateUtils.changequerystate(startDate, endDate)) {
                    doNet();
                } else {
                    this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }

        } else if (i == R.id.btnLast) {
            pageNo--;
            doNet();

        } else if (i == R.id.btnEnd) {
            pageNo = totalPages;
            doNet();

        }
    }


    private void doNet() {

        if (this.startDate == null) {
            this.showAlertDialog(this, R.string.tip, R.string.select_start_date_tip);
            return;
        }
        if (this.endDate == null) {
            this.showAlertDialog(this, R.string.tip, R.string.select_end_date_tip);
            return;
        }
        if (startDate.after(endDate)) {
            this.showAlertDialog(this, R.string.tip, R.string.select_date_tip);
            return;
        }
        sendQueryRequest(pageNo);
    }

    /**
     * 发送交易查询请求
     */
    private void sendQueryRequest(int page) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("startTime", DateUtils.formatDateToString(this.startDate, "yyyyMMddHHmmss"));
        params.put("endTime", DateUtils.formatDateToString(this.endDate, "yyyyMMddHHmmss"));
        params.put("pageSize", "5");
        params.put("pageNo", page + "");// account
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put("appCode", BaseProtocolKey.APPCODE_SUPER_TRANSFER); // 应用代码
        if (!TextUtils.isEmpty(transStatus)) {
            params.put("status", transStatus); // 查询交易状态
        }
        new QueryTransactionBillsModel().doQueryAccountBillsPost(this, params, new BusinessEngineListener<QueryTransactionBillsBean>() {
            @Override
            public void callbackBusinessResponse(QueryTransactionBillsBean bean) {
                Double amounts = Double.valueOf(bean.getAmounts());

                ll_amount_pages.setVisibility(View.VISIBLE);

                if (amounts == null || amounts.intValue() <= 0) {
                    tvAmounts.setText("");
                } else {
                    tvAmounts.setText(Html.fromHtml(getString(R.string.infoamounts, getResources().getColor(R.color.light_blue), CommonUtils.formatMoney(amounts / 100))));
                }
                // 总笔数
                // Double items = (Double) luaTable.rawget("items");
                Double items = Double.valueOf(bean.getItems());
                if (items == null || items.intValue() <= 0) {
                    tvItems.setText("");
                } else {
                    tvItems.setText(Html.fromHtml(getString(R.string.infoitems, getResources().getColor(R.color.light_blue), items.intValue())));
                }
                totalPages = CommonUtils.objectToInt(bean.getTotalPages());
                List<AccountTransfer> list = bean.getList();
                if (list != null && list.size() > 0) {
                    bills.clear();
                    for (AccountTransfer transfer : list) {
                        Bill bill = CommonUtils.generateBill(transfer, null);
                        bills.add(bill);
                    }
                    fastTransferAdapter.setBills(bills);
                    fast_queryBillsListView.setAdapter(fastTransferAdapter);
                    fastTransferAdapter.notifyDataSetChanged();
                } else {
                    bills.clear();
                    fastTransferAdapter.setBills(bills);
                    fastTransferAdapter.notifyDataSetChanged();
                    showAlertDialog(FastTransferActivity.this, R.string.tip, R.string.no_data);
                }
                fast_queryBillsListView.setSelection(curr_position);
                tvPageInfo.setText("第" + pageNo + "页" + "  共" + totalPages + "页");
                if (totalPages < 2) {
                    queryBillsListViewFooterView.setVisibility(View.GONE);
                } else {
                    queryBillsListViewFooterView.setVisibility(View.VISIBLE);
                }
                if (pageNo == 1) {
                    btnLast.setEnabled(false);
                } else {
                    btnLast.setEnabled(true);
                }
                if (pageNo == totalPages) {
                    btnNext.setEnabled(false);
                } else {
                    btnNext.setEnabled(true);
                }
            }

        });
    }

    @Override
    public void onSwiperPlugOff() {
        // 回到HPFunction界面
        clearFactor();
        stopAdpu();
        onFunctionTab(null);
    }


    @Override
    public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
        mCalendarDialog.dismiss();
        if (this.isDatePickerDialog4StartDate) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.startDate = calendar.getTime();
            this.startDateShowTextView.setText(DateUtils.formatDateToString(startDate, "yyyy-MM-dd"));
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.endDate = new Date(calendar.getTimeInMillis() + (24 * 60 * 60 * 1000) - 1);
            this.endDateShowTextView.setText(DateUtils.formatDateToString(endDate, "yyyy-MM-dd"));
        }
    }

}
